(function () {
  const imgWidth = 220;

  const divContainerEl = document.querySelector(".container");

  function createImgs() {
    new Array(40)
      .fill()
      .map((_, i) => `./img/${i}.jpg`)
      .forEach((v) => {
        const imgEl = document.createElement("img");
        imgEl.src = v;
        imgEl.style.width = imgWidth;
        divContainerEl.appendChild(imgEl);

        // 排列每一张图片
        imgEl.onload = setPositions;
      });
  }

  function setPositions() {
    const { space, columns } = cal();
    const arr = new Array(columns).fill(0);

    Array.prototype.slice.call(divContainerEl.children).forEach((imgEl) => {
      const minTop = getMin(arr);
      imgEl.style.top = minTop + "px";
      // 改变当前列的高度
      const index = arr.indexOf(minTop);
      arr[index] += imgEl.height + space;
      const left = (index + 1) * space + index * imgWidth;
      imgEl.style.left = left + "px";
    });

    divContainerEl.style.height = Math.max(...arr) + "px";
  }

  // 获取列数和间隙
  function cal() {
    const containerWidth = divContainerEl.clientWidth;
    const columns = Math.floor(containerWidth / imgWidth);
    const spaceNumber = columns + 1;
    const leftSpace = containerWidth - columns * imgWidth;
    const space = leftSpace / spaceNumber;
    return {
      space,
      columns,
    };
  }

  function getMin(arr) {
    return Math.min(...arr);
  }

  function main() {
    createImgs();
    bindEvent();
  }

  function bindEvent() {
    window.onresize = debounce(setPositions);
  }

  function debounce(cb, timer = 500) {
    let timerId = null;
    function exec(...rest) {
      if (timerId) {
        clearTimeout(timerId);
      }
      timerId = setTimeout(() => {
        cb.apply(null, rest);
      }, timer);
    }
    return exec;
  }

  main();
})();
